require('./index.css');
var _mm = require('util/mm.js');
var _userService = require('service/user-service.js');
require('../module.js');

var errTip={
	show:function(msg){
		$('.errTip').show().html(msg);
	},
	hide:function(msg){
		$('.errTip').html('').hide();
	}
}
var userLogin = {
	init: function() {
		this.bindEvent();
	},
	bindEvent: function() {
		var _this=this;
		$('#userName').blur(function(){
			var name=$(this).val();
			_userService.checkUserName(name).done(function(res){
				console.log(111+res);
			});
		});
		
		$('#registSumit').click(function(){
			_this.submitData();
			return false;
		});
	},
	submitData: function() {

		var userName =  $.trim($('#userName').val());
		var passWord = $.trim($('#passWord').val());
		var passwordConfirm = $.trim($('#passwordConfirm').val());
		var phone = $.trim($('#phone').val());
		var email = $.trim($('#email').val());
		var question = $.trim($('#question').val());
		var answer = $.trim($('#answer').val());


		var userData = {
			username: userName,
			password: passWord,
			passwordConfirm:passwordConfirm,
			phone:phone,
			email:email,
			question:question,
			answer:answer
		};

		var checkResult=this.formValidate(userData);

		if(checkResult.flag){
			_userService.register(userData).done(function(res) {
				if(res.status==0){
					window.location.href= _mm.getUrlParam('redirect') || './index.html';
				}else{
					errTip.show(res.msg);
				}
				
			}).fail(function(error){
				errTip.show(error.statusText);
			});
		}else{
			errTip.show(checkResult.msg);
		}

	},
	formValidate:function(userData){
		var result={
			flag:false,
			msg:''
		}

		if(!_mm.validate(userData.username,'require')){
			result.msg='用户名不能为空';
			return result;
		}

		if(!_mm.validate(userData.password,'require')){
			result.msg='密码不能为空';
			return result;
		}

		if(userData.password.length<6){
			result.msg='密码不能少于6位';
			return result;
		}

		if(userData.password!=userData.passwordConfirm){
			result.msg='两次输入的密码不一致';
			return result;
		}

		if(!_mm.validate(userData.phone,'phone')){
			result.msg='请输入正确的手机号码';
			return result;
		}

		if(!_mm.validate(userData.email,'email')){
			result.msg='您输入的邮箱格式不正确';
			return result;
		}

		if(!_mm.validate(userData.question,'require')){
			result.msg='请输入您的问题';
			return result;
		}

		if(!_mm.validate(userData.answer,'require')){
			result.msg='请输入您的答案';
			return result;
		}

		result.flag=true;
		result.msg='验证通过';
		return result;
	}
}

$(function() {
	userLogin.init();
});